import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_logger_server/utils/log_utils.dart';
import 'package:path/path.dart';
import 'package:mime/mime.dart';
class WebServerUtils {
   static const String assetsBasePath = 'packages/flutter_logger_server/lib/webserver/';
static Future<void> handleReq(HttpRequest request) async {
    String path = request.requestedUri.path.replaceFirst('/', '');

    if (path == '') {
      path = 'index.html';
    }
    final name = basename(path);
    final mime = lookupMimeType(name);
    try {
      LogUtils.log('method: ${request.method}  path: ${request.requestedUri.path} pa: ${request.uri.queryParameters} head: ${request.headers.contentType.toString()}');
      final data = await _loadAsset(path);

      request.response.headers.add('Content-Type', '$mime; charset=utf-8');
      request.response.add(data.buffer.asUint8List());

      request.response.close();
    } catch (err) {
      request.response.statusCode = 404;
      request.response.close();
      LogUtils.log(err.toString());
      LogUtils.log('error == method: ${request.method}  path: ${request.requestedUri}');
    }
  }

  static Future<ByteData> _loadAsset(String path) async {
    //internal_http_server-main
    ByteData data = await rootBundle.load(join(assetsBasePath, path));
    return data;
  }

}
